<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="//at.alicdn.com/t/font_2646654_d87nflpimvt.css">
    <link rel="stylesheet" href="../css/common_h&f.css">
    <link rel="stylesheet" href="../css/shoppingCar.css">
    <script src="../js/cookie.js"></script>
    <script src="../js/ajax.js"></script>
    <script src="../js/interface.js"></script>
    <script src="../js/jquery-3.6.0.js"></script>
</head>

<body>
    <div class="header">
        <div class="header-top">
            <div class="header-top0 w1">
                <div class="headerLeft">
                    <p>
                        <span>嗨，欢迎来订花乐！</span>
                    <div class="inline">
                        <span class="linkwc">
                            <i class="iconfont icon-weixin"></i>
                            关注微信
                        </span>
                        <p class="imgHide">
                            <img class="wechat0" src="https://cs.dinghuale.com/uploads/20200706/202007061732083685.jpg"
                                alt="">
                        </p>
                    </div>
                    </p>
                </div>
                <div class="headerRight">
                    <span class="tips">
                        <a href="./reg&login.html">你好，请登录</a>
                        <a href="./reg&login.html">免费注册</a>
                    </span>
                    |
                    <a href="">订单查询</a>
                    |
                    <a href="">
                        <i class="iconfont icon-gouwuche"></i>
                        购物车
                        <!-- <span class="carnum">(0)</span> -->
                    </a>
                    |
                    <div class="inline">
                        <a href="javaScript:;">手机下单</a>
                        <span class="imgHide">
                            <img class="wechat1" src="https://upyun.dinghuale.com/public/images/xiaochengxu.png" alt="">
                        </span>

                    </div>
                </div>
            </div>
        </div>
        <div class="header-mid w1">
            <div class="barLeft fl">
                <a href="../index11.html">
                    <img src="https://upyun.dinghuale.com/uploads/images/logo.png" alt="">
                </a>
            </div>
            <div class="barMid fl">
                <div class="search-bar">
                    <input type="text" name="" id="" class="search-inp" placeholder="请输入要搜索的关键字"><button><i
                            class="iconfont icon-49"></i></button>
                </div>
                <div class="search-key">
                    <a href="">红玫瑰</a>
                    <span>|</span>
                    <a href="">蛋糕</a>
                    <span>|</span>
                    <a href="">百合</a>
                    <span>|</span>
                    <a href="">康乃馨</a>
                    <span>|</span>
                </div>
            </div>
            <div class="barRight">
                <i class="iconfont icon-dianhua_2"></i>
                <span>400-060-1520</span>
            </div>
        </div>
        <div class="header-footer w cl df">
            <div class="header-footerL">
                <div class="headerL df ">
                    <p>全部商品分类</p>
                    <i class="iconfont icon-xiangxia"> </i>
                </div>
                <div class="headerHide">
                    <div>
                        <p>用途</p>
                        <ul class="">
                            <a href="">爰情鲜花</a>
                            <a href="">生日鲜花</a>
                            <a href="">友情鲜花</a>
                            <a href="">探病问候</a>
                            <a href="">道歉鲜花</a>
                            <a href="">问候长辈</a>
                            <a href="">感谢老师</a>
                            <a href="">哀思鲜花</a>
                            <a href="">商务鲜花</a>
                        </ul>
                    </div>
                    <div>
                        <p>花材</p>
                        <ul class="">
                            <a href="">玫瑰</a>
                            <a href="">百合</a>
                            <a href="">康乃馨</a>
                            <a href="">向日葵</a>
                            <br>
                            <a href="">满天星</a>
                            <a href="">郁金香</a>
                            <a href="">菊花</a>
                            <a href="">其他</a>
                        </ul>
                    </div>
                    <div>
                        <p>类别</p>
                        <ul class="">
                            <a href="">花束</a>
                            <a href="">礼盒</a>
                            <a href="">蛋糕</a>
                            <a href="">花篮</a>
                            <a href="">绿植</a>
                            <a href="">周花</a>
                            <a href="">手提花篮</a>
                            <a href="">桌花</a>
                            <a href="">其他</a>
                        </ul>
                    </div>
                    <div>
                        <p>枝数</p>
                        <ul class="laa">
                            <a href="">11枝</a>
                            <a href="">19枝</a>
                            <a href="">21枝</a>
                            <a href="">33枝</a>
                            <br>
                            <a href="">52枝</a>
                            <a href="">66枝</a>
                            <a href="">99枝</a>
                            <a href="">其他</a>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="navList cl ">
                <a href="">鲜花</a>
                <a href="">花束</a>
                <a href="">礼盒</a>
                <a href="">蛋糕</a>
                <a href="">花篮</a>
                <a href="">绿植</a>
                <a href="">周花</a>
            </div>
        </div>

    </div>
    <div class="catbox cl">
        <table id="cartTable w">
            <thead>
                <tr>
                    <th>
                        <label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选
                        </label>
                    </th>
                    <th>商品信息</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr data-id="1">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="https://upyun.dinghuale.com/uploads/20210426/202104261310519646.jpg"
                            alt="" /><span>满天繁星</span></td>
                    <td class="price">229.00</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">229.00</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr data-id="2">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="https://upyun.dinghuale.com/uploads/20210426/202104261052034321.jpg"
                            alt="" /><span>粉色公主</span></td>
                    <td class="price">169.00</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">169.00</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr data-id="3">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="https://upyun.dinghuale.com/uploads/20210426/202104261339329479.jpg"
                            alt="" /><span>你是唯一</span></td>
                    <td class="price">659.00</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">659.00</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr data-id="4">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="https://upyun.dinghuale.com/uploads/20210426/202104261259483341.jpg"
                            alt="" /><span>一生守候</span></td>
                    <td class="price">319.00</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">319.00</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">
            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>

            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件
            </div>
        </div>
    </div>
    <div class="footer cl">

    </div>
</body>
<script src="../js/common_h&f.js"></script>
<script>
    //引入尾部
    $(".footer").load("./common_footer.html");

    $(".search-key a").attr("href", "./goodsList.html");
    $(".headerHide a").attr("href", "./goodsList.html");
    $(".navList a").attr("href", "./goodsList.html");

    //标识用户身份
    var tips = document.getElementsByClassName("tips")[0];
    var user = getCookie("lgc");
    if (user) {
        tips.innerHTML = `欢迎您,${user} <a onsubmit="return false" onclick="exit()">退出</a>`;
    }
    function exit() {
        delCookie("lgc");
        location.reload();
    }



    var catbox = document.getElementsByClassName("catbox")[0];
    var tbody = catbox.getElementsByTagName("tbody")[0];
    loadShoppingCar();
    async function loadShoppingCar() {
        var result = await searchShoppingCarByUser({ user });
        console.log(result);
        var { status, detail, list } = result;
        if (status) {
            var html = "";
            list.forEach(({ id, gId, goodsName, goodsPrice, goodsImg, buyNum, total }) => {
                html += `<tr data-id="${id}">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsName}</span>
                    </td>
                    <td class="price">${goodsPrice}</td>
                    <td class="count"><span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${total}</td>
                    <td class="operation"><span class="delete" >删除</span></td>
                </tr>`
            })
            tbody.innerHTML = html;
        } else {
            catbox.innerHTML = "<img src='https://www.dinghuale.com/public/images/cartback.png' alt='' class='kongShoppingCar' /><p class='kongTips'>暂无商品&emsp;&emsp;是否<a href='./goodsList.html'>采购商品</a>？</p>";
        }

        // var carnum = 0
        // carnum += $(".count-input").val() * 1
        // console.log(carnum);
        // console.log($(".count-input").val());
    }



    // console.log($(".carnum").html() * 1);

    var catbox = document.getElementsByClassName("catbox")[0];
    var checkAll = document.getElementsByClassName("check-all")[0];
    var checkOneList = document.getElementsByClassName("check-one");

    catbox.onclick = async function (e) {

        // console.log(11111);
        var e = e || window.event;
        var target = e.target || e.srcElement;
        // console.log(target);
        if (target.classList.contains("check-all")) {
            console.log("点击全选");
            checkAllHandler(target);
            getTotal();
        } else if (target.classList.contains("check-one")) {
            isAllChecked();
            getTotal();


        } else if (target.classList.contains("add")) {
            var parentTr = parent(parent(target));
            var id = parentTr.dataset.id;
            var result = await updateShoppingCarById({ id, type: 1 });
            var { status, detail } = result;
            if (status) {
                console.log("点击加号");
                addHandler(target);
                getTotal();
            } else {
                alert(detail);
            }

        } else if (target.classList.contains("reduce")) {

            var countInput = next(target);
            console.log(countInput);

            // a. 输入框  数量 减一 
            var num = countInput.value;

            // c.   减之前  判断  如果数量为1  不能减
            if (num <= 1) {
                return false; // 
            }

            var parentTr = parent(parent(target));
            var id = parentTr.dataset.id;
            var result = await updateShoppingCarById({ id, type: 0 });
            var { status, detail } = result;
            if (status) {
                console.log("点击加号");
                reduceHandler(target);
                getTotal();
            } else {
                alert(detail);
            }

        } else if (target.classList.contains("delete")) {
            deleteOneHandler(target);
            isAllChecked();
            getTotal();
        } else if (target.id == "deleteAll") {
            deleteAllHandler();
            isAllChecked();
            getTotal();
        }

    }

    function checkAllHandler(target) {
        var status = target.checked;
        console.log(status);
        for (var i = 0; i < checkOneList.length; i++) {
            var checkOne = checkOneList[i];
            checkOne.checked = status;
        }
    }
    function isAllChecked() {
        // 每次点击单选  判断所有的单选框是否全部被选中 
        var flag = true; // 假设全部被选中    =>  只要有一个没被选中即可推翻假设
        for (var j = 0; j < checkOneList.length; j++) {
            var checkOne = checkOneList[j];  // 获取每一个
            // console.log(checkOne);
            if (!checkOne.checked) {   // checkOne.checked == false   存在未被选中的
                flag = false;
                break;
            }
        }
        checkAll.checked = checkOneList.length == 0 ? false : flag;
    }

    async function addHandler(target) {
        // console.log(add, target);
        // console.log(target);      // 被点击的加号
        // target.previousElementSibling
        // debugger;

        //  (1) 商品数量加1 (被点击的加号前的)
        var countInput = prev(target);    // 被点击的加号 前的 countInp
        // console.log(countInput);
        var num = countInput.value;   // 取值 num
        num++;                        //自增
        countInput.value = num;       // 更新到页面

        // countInput.value++;

        // (2) 小计更新
        // target.parentElement
        var countTd = parent(target);   // 获取被点击加号的父元素

        var priceTd = prev(countTd);   // 找到父元素的前一个 
        var subtotalTd = next(countTd); // 

        var price = priceTd.textContent;
        var subtotal = num * price;

        console.log(price, subtotal);

        subtotalTd.textContent = subtotal.toFixed(2);


        //  减号按钮的 "-" 显示  
        var reduce = prev(countInput);
        reduce.textContent = "-";


    }
    function reduceHandler(target) {
        // console.log(target);
        var countInput = next(target);
        console.log(countInput);

        // a. 输入框  数量 减一 
        var num = countInput.value;

        // c.   减之前  判断  如果数量为1  不能减
        if (num == 1) {
            return false; // 
        }

        num--; // 自减

        if (num == 1) {
            target.textContent = "";
        }

        countInput.value = num;

        // b. 小计更新  =  单价*数量
        var parentTd = parent(target);
        var priceTd = prev(parentTd);
        var subtotalTd = next(parentTd);

        var price = priceTd.textContent * 1;

        var subtotal = price * num;

        subtotalTd.textContent = subtotal.toFixed(2);
    }
    async function deleteOneHandler(target) {
        if (confirm("是否删除该商品?")) {
            // target.remove();
            // var parentTd = parent(target);
            // var parentTr = parent(parentTd);
            var parentTr = parent(parent(target));
            // var id = parentTr.getAttribute("data-id");
            var id = parentTr.dataset.id;
            console.log(parentTr);

            var result = await deleteShoppingCarById({ id });
            var { status, detail } = result;
            if (status) {
                parentTr.remove();
            } else {
                alert(detail)
            }

        }
    }
    async function deleteAllHandler() {
        var list = [];
        for (let i = 0; i < checkOneList.length; i++) {
            let checkOne = checkOneList[i];
            if (checkOne.checked) {
                var parentTr = parent(parent(checkOne));
                var id = parentTr.dataset.id;
                list.push(id);
                console.log(parentTr);
                parentTr.remove();
                i--;
            }
        }
        console.log(list);

        var result = await deleteShoppingCarById({ id: list.join(",") });
        var { status, detail } = result;
        if (status) {
            alert(detail)
        } else {
            alert(detail)
        }
    }

    function getTotal() {
        // 只要涉及到购买的商品数量变化  都需要重新结算
        // 结算功能  => 找到所有选中状态的单选框 => 对应找出购买的商品的数量和小计  => 累加  => 输出
        console.log("结算中");
        var sum = 0;
        var allPrice = 0;
        for (let i = 0; i < checkOneList.length; i++) {
            let checkOne = checkOneList[i];
            if (checkOne.checked) {  // 如果单选框被选中
                var tr = parent(parent(checkOne));
                var countInput = tr.getElementsByClassName("count-input")[0];
                var subtotalTd = tr.getElementsByClassName("subtotal")[0];

                var num = countInput.value * 1;
                var subtotal = subtotalTd.textContent * 1

                sum += num;
                allPrice += subtotal;

            }
        }

        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }

    function parent(ele) {
        return ele.parentElement || ele.parentNode;
    }

    function prev(ele) {
        return ele.previousElementSibling || ele.previousSibling;
    }

    function next(ele) {
        return ele.nextElementSibling || ele.nextSibling;
    }

    // $(function () {
    //     $(".check-all").click(function () {
    //         var status = $(this).prop("checked");
    //         $(".check-one").prop("checked", status);
    //         getTotal()
    //     })

    //     $(".check-one").click(function () {
    //         var flag = $(".check-one").is(":not(:checked)")
    //         $(".check-all").prop("checked", !flag);
    //         getTotal();
    //     })

    //     $(".add").click(function () {
    //         var num = $(this).prev().val();
    //         num++;
    //         $(this).prev().val(num);
    //         var price = $(this).parent().prev().text();
    //         $(this).parent().next().text((price * num).toFixed(2));
    //         $(this).prevAll(".reduce").text("-");
    //         getTotal();
    //     })

    //     $(".reduce").click(function () {
    //         var num = $(this).next().val();
    //         if (num <= 1) return false;
    //         num--;
    //         if (num == 1) {
    //             $(this).text("");
    //         }
    //         $(this).next().val(num);
    //         var price = $(this).parent().prev().text();
    //         $(this).parent().next().text((price * num).toFixed(2));
    //         getTotal();

    //     })

    //     $(".delete").click(function () {
    //         if (confirm("是否删除该商品?")) {
    //             $(this).parents("tr").remove();
    //             isAllChecked();
    //             getTotal();
    //         }
    //     })

    //     $("#deleteAll").click(function () {
    //         var list = $(".check-one:checked").parents("tr").map(function () {
    //             return $(this).prop("dataset").id;
    //         }).get();
    //         console.log(list.join(","));

    //         $(".check-one:checked").parents("tr").remove();
    //         isAllChecked();
    //         getTotal();
    //     })

    //     function isAllChecked() {
    //         var flag = $(".check-one").is(":not(:checked)");
    //         $(".check-all").prop("checked", $(".check-one").length > 0 ? !flag : false);
    //     }

    //     function getTotal() {
    //         var sum = 0;
    //         var allPrice = 0;
    //         $(".check-one:checked").parents("tr").each(function () {
    //             var num = $(this).find(".count-input").val() * 1;
    //             var subtotal = $(this).find(".subtotal").text() * 1;
    //             sum += num;
    //             allPrice += subtotal;
    //         })
    //         $("#selectedTotal").text(sum);
    //         $("#priceTotal").text(allPrice.toFixed(2));
    //     }
    // })



</script>

</html>